package com.thread.exe;

public class StripedMap {
	private static final int N_LOCKS = 16;
	private final Node[] buckets;
	private final Object[] locks;
	
	private static class Node{
		public Node next;
		public Object value;
		public Object key;
	}

	public StripedMap(int numBuckets) {
		super();
		this.buckets = new Node[numBuckets];
		this.locks = new Object[N_LOCKS];
		for (int i = 0; i < numBuckets; i++) {
			locks[i] = new Object();
		}
	}
	
	private final int hash(Object key) {
		return Math.abs(key.hashCode() % buckets.length);
	}
	
	public Object get(Object key) {
		int hash = hash(key);
		synchronized (locks[hash % N_LOCKS]) {
			for(Node t = buckets[hash]; t != null; t = t.next) {
				if(t.key.equals(key)) {
					return t.value;
				}
			}
		}
		return null;
	}
	
	public void clear() {
		for (int i = 0; i < buckets.length; i++) {
			synchronized (locks[i % N_LOCKS]) {
				buckets[i] = null;
			}
		}
	}
} 
